#include "alertmanager.h"
#include "ui_alertmanager.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QMessageBox>
#include <QInputDialog>
#include <QDateTime>
#include <QDebug>
#include <QSettings>
#include <QFileDialog>
#include <QStandardPaths>
#include "logmanager.h"
#include "ruleeditordialog.h"
#include <QJsonObject>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonValue>
#include "datamonitor.h"
#include "page_control.h"

AlertManager::AlertManager(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::AlertManager),
    currentAlertsModel(nullptr),
    alertHistoryModel(nullptr),
    alertRulesModel(nullptr),
    alertCheckTimer(nullptr),
    m_dataMonitor(nullptr),      // ✅ 新增
    m_pageControl(nullptr)        // ✅ 新增
{
    ui->setupUi(this);
    setupUI();
    setupConnections();
    setupModels();
    setupAlertCheckTimer();
    LogManager::logSystem("告警管理模块", "告警管理模块初始化完成");
}

// ✅ 新增：设置DataMonitor引用
void AlertManager::setDataMonitor(DataMonitor *dataMonitor)
{
    m_dataMonitor = dataMonitor;
    LogManager::logSystem("告警管理模块", "DataMonitor已连接");
}

// ✅ 新增：设置Page_control引用
void AlertManager::setPageControl(Page_control *pageControl)
{
    m_pageControl = pageControl;
    LogManager::logSystem("告警管理模块", "Page_control已连接");
}


AlertManager::~AlertManager()
{
    LogManager::logSystem("告警管理模块", "告警管理模块销毁");

    delete ui;
    if (currentAlertsModel) delete currentAlertsModel;
    if (alertHistoryModel) delete alertHistoryModel;
    if (alertRulesModel) delete alertRulesModel;
    if (alertCheckTimer) delete alertCheckTimer;
}

void AlertManager::setupUI()
{
    QDateTime currentTime = QDateTime::currentDateTime();
    ui->dateTimeEditHistoryStart->setDateTime(currentTime.addDays(-7));
    ui->dateTimeEditHistoryEnd->setDateTime(currentTime);

    ui->tableViewCurrentAlerts->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableViewCurrentAlerts->setSelectionMode(QAbstractItemView::SingleSelection);
    ui->tableViewAlertHistory->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui->tableViewAlertRules->setSelectionBehavior(QAbstractItemView::SelectRows);

    ui->tableViewAlertRules->setEditTriggers(QAbstractItemView::DoubleClicked | QAbstractItemView::EditKeyPressed);
}

void AlertManager::setupConnections()
{
    connect(ui->btnAddRule, &QPushButton::clicked, this, &AlertManager::onAddRule);
    connect(ui->btnDeleteRule, &QPushButton::clicked, this, &AlertManager::onDeleteRule);
    connect(ui->btnSaveRules, &QPushButton::clicked, this, &AlertManager::onSaveRules);
    connect(ui->btnImportRules, &QPushButton::clicked, this, &AlertManager::onImportRules);
    connect(ui->btnExportRules, &QPushButton::clicked, this, &AlertManager::onExportRules);
    connect(ui->btnAcknowledge, &QPushButton::clicked, this, &AlertManager::onAcknowledgeAlert);
    connect(ui->btnResolve, &QPushButton::clicked, this, &AlertManager::onResolveAlert);
    connect(ui->btnQueryHistory, &QPushButton::clicked, this, &AlertManager::onQueryHistory);
    connect(ui->comboBoxAlertStatus, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &AlertManager::onAlertStatusChanged);
    connect(ui->checkBoxEnabled, &QCheckBox::stateChanged, this, &AlertManager::onRuleFilterChanged);
    connect(ui->tableViewAlertRules, &QTableView::doubleClicked, this, &AlertManager::onEditRule);

}

void AlertManager::setupModels()
{
    // 设置当前告警模型
    currentAlertsModel = new QSqlTableModel(this);
    currentAlertsModel->setTable("alarm_records");
    currentAlertsModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    if (currentAlertsModel->select()) {
        currentAlertsModel->setHeaderData(currentAlertsModel->fieldIndex("record_id"), Qt::Horizontal, "记录ID");
        currentAlertsModel->setHeaderData(currentAlertsModel->fieldIndex("rule_id"), Qt::Horizontal, "规则ID");
        currentAlertsModel->setHeaderData(currentAlertsModel->fieldIndex("device_id"), Qt::Horizontal, "设备ID");
        currentAlertsModel->setHeaderData(currentAlertsModel->fieldIndex("trigger_value"), Qt::Horizontal, "触发值");
        currentAlertsModel->setHeaderData(currentAlertsModel->fieldIndex("trigger_time"), Qt::Horizontal, "触发时间");
        currentAlertsModel->setHeaderData(currentAlertsModel->fieldIndex("status"), Qt::Horizontal, "状态");
        currentAlertsModel->setHeaderData(currentAlertsModel->fieldIndex("resolved_time"), Qt::Horizontal, "解决时间");

        ui->tableViewCurrentAlerts->setModel(currentAlertsModel);
        ui->tableViewCurrentAlerts->resizeColumnsToContents();

        currentAlertsModel->setFilter("status IN ('active', 'acknowledged')");
        currentAlertsModel->select();

        LogManager::logSystem("告警管理模块", "当前告警模型加载成功");
    } else {
        qDebug() << "当前告警模型查询失败:" << currentAlertsModel->lastError().text();
        LogManager::logError("告警管理: 当前告警模型查询失败");
    }

    // 设置历史告警模型
    alertHistoryModel = new QSqlTableModel(this);
    alertHistoryModel->setTable("alarm_records");
    alertHistoryModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    if (alertHistoryModel->select()) {
        alertHistoryModel->setHeaderData(alertHistoryModel->fieldIndex("record_id"), Qt::Horizontal, "记录ID");
        alertHistoryModel->setHeaderData(alertHistoryModel->fieldIndex("rule_id"), Qt::Horizontal, "规则ID");
        alertHistoryModel->setHeaderData(alertHistoryModel->fieldIndex("device_id"), Qt::Horizontal, "设备ID");
        alertHistoryModel->setHeaderData(alertHistoryModel->fieldIndex("trigger_value"), Qt::Horizontal, "触发值");
        alertHistoryModel->setHeaderData(alertHistoryModel->fieldIndex("trigger_time"), Qt::Horizontal, "触发时间");
        alertHistoryModel->setHeaderData(alertHistoryModel->fieldIndex("status"), Qt::Horizontal, "状态");
        alertHistoryModel->setHeaderData(alertHistoryModel->fieldIndex("resolved_time"), Qt::Horizontal, "解决时间");

        ui->tableViewAlertHistory->setModel(alertHistoryModel);
        ui->tableViewAlertHistory->resizeColumnsToContents();

        QDateTime oneWeekAgo = QDateTime::currentDateTime().addDays(-7);
        alertHistoryModel->setFilter(QString("trigger_time >= '%1'").arg(oneWeekAgo.toString("yyyy-MM-dd HH:mm:ss")));
        alertHistoryModel->select();

        ui->tableViewAlertRules->horizontalHeader()->setStretchLastSection(true);


        LogManager::logSystem("告警管理模块", "历史告警模型加载成功");
    } else {
        qDebug() << "历史告警模型查询失败:" << alertHistoryModel->lastError().text();
        LogManager::logError("告警管理: 历史告警模型查询失败");
    }

    // 设置告警规则模型
    alertRulesModel = new QSqlTableModel(this);
    alertRulesModel->setTable("alarm_rules");
    alertRulesModel->setEditStrategy(QSqlTableModel::OnManualSubmit);

    if (alertRulesModel->select()) {
        alertRulesModel->setHeaderData(alertRulesModel->fieldIndex("rule_id"), Qt::Horizontal, "规则ID");
        alertRulesModel->setHeaderData(alertRulesModel->fieldIndex("device_id"), Qt::Horizontal, "设备ID");
        alertRulesModel->setHeaderData(alertRulesModel->fieldIndex("description"), Qt::Horizontal, "规则描述");
        alertRulesModel->setHeaderData(alertRulesModel->fieldIndex("condition"), Qt::Horizontal, "触发条件");
        alertRulesModel->setHeaderData(alertRulesModel->fieldIndex("action"), Qt::Horizontal, "执行动作");
        alertRulesModel->setHeaderData(alertRulesModel->fieldIndex("severity"), Qt::Horizontal, "严重程度");
        alertRulesModel->setHeaderData(alertRulesModel->fieldIndex("is_enabled"), Qt::Horizontal, "是否启用");
        alertRulesModel->setHeaderData(alertRulesModel->fieldIndex("created_at"), Qt::Horizontal, "创建时间");

        ui->tableViewAlertRules->setModel(alertRulesModel);
        ui->tableViewAlertRules->resizeColumnsToContents();

        alertRulesModel->setFilter("is_enabled = 1");
        alertRulesModel->select();

        LogManager::logSystem("告警管理模块",
                            QString("告警规则模型加载成功,共%1条规则").arg(alertRulesModel->rowCount()));
    } else {
        qDebug() << "告警规则模型查询失败:" << alertRulesModel->lastError().text();
        LogManager::logError("告警管理: 告警规则模型查询失败");
        QMessageBox::warning(this, "警告",
                           "告警规则表查询失败,请检查数据库表结构。\n错误信息: " +
                           alertRulesModel->lastError().text());
    }

    checkDatabaseTables();
}

void AlertManager::checkDatabaseTables()
{
    QSqlQuery query;
    QStringList requiredTables = {"alarm_rules", "alarm_records"};

    for (const QString& tableName : requiredTables) {
        if (!query.exec(QString("SELECT name FROM sqlite_master WHERE type='table' AND name='%1'").arg(tableName))) {
            qDebug() << "检查表" << tableName << "失败:" << query.lastError().text();
            LogManager::logError(QString("告警管理: 检查表%1失败").arg(tableName));
            continue;
        }

        if (query.next()) {
            qDebug() << "表" << tableName << "存在";
            LogManager::logSystem("告警管理模块", QString("表%1存在").arg(tableName));
        } else {
            qDebug() << "表" << tableName << "不存在";
            LogManager::logError(QString("告警管理: 表%1不存在").arg(tableName));
            QMessageBox::warning(this, "警告",
                               QString("数据库表 %1 不存在,告警功能将无法正常工作。").arg(tableName));
        }
    }
}

void AlertManager::applyUserPermissions()
{
    if (currentUserRole == "user") {
        ui->btnAddRule->setEnabled(false);
        ui->btnDeleteRule->setEnabled(false);
        ui->btnSaveRules->setEnabled(false);
        ui->btnImportRules->setEnabled(false);
        ui->btnExportRules->setEnabled(true);

        ui->tableViewAlertRules->setEditTriggers(QAbstractItemView::NoEditTriggers);

        ui->btnAcknowledge->setEnabled(true);
        ui->btnResolve->setEnabled(true);
        ui->btnQueryHistory->setEnabled(true);
    }
}

void AlertManager::setupAlertCheckTimer()
{
    alertCheckTimer = new QTimer(this);
    connect(alertCheckTimer, &QTimer::timeout, this, &AlertManager::refreshAlerts);
    alertCheckTimer->start(5000);
    LogManager::logSystem("告警管理模块", "告警检查定时器已启动");
}

void AlertManager::checkAlerts(const QVariantMap& sensorData)
{
    QSqlQuery query;
    query.prepare("SELECT rule_id, device_id, description, condition, action, severity "
                  "FROM alarm_rules WHERE is_enabled = 1");

    if (query.exec()) {
        int checkedCount = 0;
        int triggeredCount = 0;
        int autoResolvedCount = 0;

        while (query.next()) {
            int ruleId = query.value(0).toInt();
            int deviceId = query.value(1).toInt();
            QString description = query.value(2).toString();
            QString condition = query.value(3).toString();
            QString action = query.value(4).toString();
            QString severity = query.value(5).toString();

            if (sensorData["device_id"].toInt() != deviceId) {
                continue;
            }

            checkedCount++;

            if (evaluateAlertCondition(condition, sensorData)) {
                // 条件满足，触发告警
                triggerAlert(ruleId, sensorData);
                triggeredCount++;
            } else {
                // ✅ 条件不满足，尝试自动解决告警
                if (m_activeAlertsByRule.contains(ruleId)) {
                    autoResolveAlert(ruleId, sensorData);
                    autoResolvedCount++;
                }
            }
        }

        if (autoResolvedCount > 0) {
            LogManager::logSystem("告警管理模块",
                                QString("检查了%1条规则,触发了%2条告警,自动解决了%3条告警")
                                .arg(checkedCount).arg(triggeredCount).arg(autoResolvedCount));
        } else if (triggeredCount > 0 || checkedCount % 10 == 0) {
            LogManager::logSystem("告警管理模块",
                                QString("检查了%1条规则,触发了%2条告警").arg(checkedCount).arg(triggeredCount));
        }
    } else {
        LogManager::logError("告警管理: 检查告警规则失败");
    }
}


void AlertManager::setCurrentUserRole(const QString &role)
{
    this->currentUserRole = role;
    applyUserPermissions();
}

bool AlertManager::evaluateAlertCondition(const QString& condition, const QVariantMap& data)
{
    QStringList parts = condition.split(" ");
    if (parts.size() < 3) return false;

    QString field = parts[0];
    QString op = parts[1];
    double threshold = parts[2].toDouble();

    if (!data.contains(field)) return false;

    double value = data[field].toDouble();

    if (op == ">") return value > threshold;
    if (op == ">=") return value >= threshold;
    if (op == "<") return value < threshold;
    if (op == "<=") return value <= threshold;
    if (op == "==") return value == threshold;
    if (op == "!=") return value != threshold;

    return false;
}

void AlertManager::triggerAlert(int ruleId, const QVariantMap& sensorData)
{
    // 检查是否已有活跃的告警
    QSqlQuery checkQuery;
    checkQuery.prepare("SELECT record_id FROM alarm_records "
                      "WHERE rule_id = ? AND status IN ('active', 'acknowledged')");
    checkQuery.addBindValue(ruleId);

    if (checkQuery.exec() && checkQuery.next()) {
        // 已有活跃告警，不重复触发
        return;
    }

    // 插入新的告警记录
    QSqlQuery insertQuery;
    insertQuery.prepare("INSERT INTO alarm_records (rule_id, device_id, trigger_value, trigger_time, status) "
                       "VALUES (?, ?, ?, ?, 'active')");
    insertQuery.addBindValue(ruleId);
    insertQuery.addBindValue(sensorData["device_id"].toInt());

    // 根据数据类型提取触发值
    double triggerValue = 0.0;
    if (sensorData.contains("temperature")) {
        triggerValue = sensorData["temperature"].toDouble();
    } else if (sensorData.contains("humidity")) {
        triggerValue = sensorData["humidity"].toDouble();
    } else if (sensorData.contains("light")) {
        triggerValue = sensorData["light"].toDouble();
    } else if (sensorData.contains("co2")) {
        triggerValue = sensorData["co2"].toDouble();
    } else if (sensorData.contains("pressure")) {
        triggerValue = sensorData["pressure"].toDouble();
    }

    insertQuery.addBindValue(triggerValue);
    insertQuery.addBindValue(QDateTime::currentDateTime());

    if (insertQuery.exec()) {
        int recordId = insertQuery.lastInsertId().toInt();

        // ✅ 记录活跃告警
        m_activeAlertsByRule[ruleId] = recordId;

        // 获取规则详情
        QSqlQuery ruleQuery;
        ruleQuery.prepare("SELECT description, severity, condition FROM alarm_rules WHERE rule_id = ?");
        ruleQuery.addBindValue(ruleId);

        if (ruleQuery.exec() && ruleQuery.next()) {
            QString description = ruleQuery.value(0).toString();
            QString severity = ruleQuery.value(1).toString();
            QString condition = ruleQuery.value(2).toString();

            QString alertMessage = QString("【%1】%2 - 设备ID: %3, 当前值: %4")
                                  .arg(severity)
                                  .arg(description)
                                  .arg(sensorData["device_id"].toInt())
                                  .arg(triggerValue);

            // ✅ 第一步：立即触发告警信号（不等待用户交互）
            emit alertTriggered(alertMessage);

            // ✅ 第二步：立即激活蜂鸣器（不等待用户交互）
            activateBuzzer();

            // ✅ 第三步：立即记录告警日志（不等待用户交互）
            LogManager::logAlarm(
                recordId,
                QString("规则ID:%1 | 设备ID:%2 | 触发条件:%3 | 当前值:%4 | 严重程度:%5 | 描述:%6")
                .arg(ruleId)
                .arg(sensorData["device_id"].toInt())
                .arg(condition)
                .arg(triggerValue)
                .arg(severity)
                .arg(description),
                -1,
                sensorData["device_id"].toInt()
            );

            // ✅ 第四步：最后显示告警对话框（仅作为用户通知，不影响告警已触发的事实）
            showAlertDialog(alertMessage);
        }

        // 刷新当前告警列表
        currentAlertsModel->select();
    } else {
        LogManager::logError(QString("告警管理: 触发告警失败,规则ID: %1").arg(ruleId));
    }
}


void AlertManager::showAlertDialog(const QString& message)
{
    QMessageBox alertBox;
    alertBox.setWindowTitle("告警通知");
    alertBox.setText(message);
    alertBox.setIcon(QMessageBox::Warning);
    alertBox.addButton("查看详情", QMessageBox::AcceptRole);
    alertBox.addButton("忽略", QMessageBox::RejectRole);

    if (alertBox.exec() == QMessageBox::AcceptRole) {
        LogManager::logOperation(-1, "告警处理", "用户查看了告警详情");
    } else {
        LogManager::logOperation(-1, "告警处理", "用户忽略了告警");
    }
}

void AlertManager::onAddRule()
{
    RuleEditorDialog dialog(this);
    if (dialog.exec() == QDialog::Accepted) {
        QVariantMap data = dialog.getRuleData();

        int row = alertRulesModel->rowCount();
        alertRulesModel->insertRow(row);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("device_id")), data["device_id"]);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("description")), data["description"]);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("condition")), data["condition"]);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("action")), data["action"]);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("severity")), data["severity"]);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("is_enabled")), data["is_enabled"]);
        alertRulesModel->submitAll();
        alertRulesModel->select();
        ui->statusbar->showMessage("已添加新告警规则");
    }
}
void AlertManager::onEditRule()
{
    QModelIndex index = ui->tableViewAlertRules->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请选择要修改的规则");
        return;
    }

    int row = index.row();
    QVariantMap rule;
    rule["device_id"] = alertRulesModel->data(alertRulesModel->index(row, alertRulesModel->fieldIndex("device_id")));
    rule["description"] = alertRulesModel->data(alertRulesModel->index(row, alertRulesModel->fieldIndex("description")));
    rule["condition"] = alertRulesModel->data(alertRulesModel->index(row, alertRulesModel->fieldIndex("condition")));
    rule["action"] = alertRulesModel->data(alertRulesModel->index(row, alertRulesModel->fieldIndex("action")));
    rule["severity"] = alertRulesModel->data(alertRulesModel->index(row, alertRulesModel->fieldIndex("severity")));
    rule["is_enabled"] = alertRulesModel->data(alertRulesModel->index(row, alertRulesModel->fieldIndex("is_enabled")));

    RuleEditorDialog dialog(this);
    dialog.setEditData(rule);
    if (dialog.exec() == QDialog::Accepted) {
        QVariantMap data = dialog.getRuleData();
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("device_id")), data["device_id"]);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("description")), data["description"]);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("condition")), data["condition"]);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("action")), data["action"]);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("severity")), data["severity"]);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("is_enabled")), data["is_enabled"]);
        alertRulesModel->submitAll();
        ui->statusbar->showMessage("规则已更新");
    }
}


void AlertManager::onDeleteRule()
{
    if (!alertRulesModel) {
        QMessageBox::warning(this, "警告", "告警规则模型未初始化");
        LogManager::logError("删除告警规则失败: 模型未初始化");
        return;
    }

    QModelIndex index = ui->tableViewAlertRules->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请选择要删除的规则");
        LogManager::logError("删除告警规则失败: 未选择规则");
        return;
    }

    int row = index.row();
    QString description = alertRulesModel->data(alertRulesModel->index(row, alertRulesModel->fieldIndex("description"))).toString();
    int ruleId = alertRulesModel->data(alertRulesModel->index(row, alertRulesModel->fieldIndex("rule_id"))).toInt();

    if (QMessageBox::question(this, "确认删除", QString("确定要删除规则 '%1' (ID: %2) 吗?").arg(description).arg(ruleId)) == QMessageBox::Yes) {
        LogManager::logOperation(-1, "删除告警规则",
                               QString("确认删除规则: %1 (ID: %2)").arg(description).arg(ruleId));

        // 从INI文件中删除
        deleteRuleFromIni(ruleId);

        alertRulesModel->removeRow(row);
        ui->statusbar->showMessage("规则已标记删除,请保存更改生效");
        LogManager::logOperation(-1, "删除告警规则", "规则已标记删除");
    } else {
        LogManager::logOperation(-1, "删除告警规则", "用户取消删除操作");
    }
}

void AlertManager::onSaveRules()
{
    if (!alertRulesModel) {
        QMessageBox::warning(this, "警告", "告警规则模型未初始化");
        LogManager::logError("保存告警规则失败: 模型未初始化");
        return;
    }

    LogManager::logOperation(-1, "保存告警规则", "开始保存告警规则更改");

    if (alertRulesModel->submitAll()) {
        // 同步所有规则到INI文件
        QSqlQuery query;
        query.prepare("SELECT rule_id FROM alarm_rules");
        if (query.exec()) {
            while (query.next()) {
                int ruleId = query.value(0).toInt();
                syncRuleToIni(ruleId);
            }
        }

        ui->statusbar->showMessage("告警规则保存成功");
        LogManager::logOperation(-1, "保存告警规则",
                               QString("告警规则保存成功,共%1条规则").arg(alertRulesModel->rowCount()));
    } else {
        QString error = alertRulesModel->lastError().text();
        QMessageBox::critical(this, "错误", "保存告警规则失败: " + error);
        LogManager::logError("保存告警规则失败: " + error);
    }
}

bool AlertManager::importRulesFromIni(const QString& filename)
{
    QSettings settings(filename, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");

    if (!QFile::exists(filename)) {
        QMessageBox::warning(this, "错误", "规则文件不存在：" + filename);
        LogManager::logError("导入规则失败：文件不存在：" + filename);
        return false;
    }

    QStringList groups = settings.childGroups();
    if (groups.isEmpty()) {
        QMessageBox::warning(this, "提示", "没有找到任何规则组。");
        LogManager::logError("导入规则失败：INI文件无有效规则组");
        return false;
    }

    int importedCount = 0;
    int skippedCount = 0;

    for (const QString& group : groups) {
        settings.beginGroup(group);

        QString deviceId   = settings.value("device_id").toString().trimmed();
        QString description = settings.value("description").toString().trimmed();
        QString condition  = settings.value("condition").toString().trimmed();
        QString action     = settings.value("action").toString().trimmed();
        QString severity   = settings.value("severity").toString().trimmed();

        // 字段完整性检查
        if (deviceId.isEmpty() || description.isEmpty() || condition.isEmpty()) {
            qWarning() << "跳过无效规则组:" << group << "(字段不完整)";
            settings.endGroup();
            skippedCount++;
            continue;
        }

        // 重复检查
        if (isRuleExists(deviceId, description, condition, action, severity)) {
            qDebug() << "跳过重复规则:" << description;
            settings.endGroup();
            skippedCount++;
            continue;
        }

        // 插入新规则
        int row = alertRulesModel->rowCount();
        alertRulesModel->insertRow(row);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("device_id")), deviceId);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("description")), description);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("condition")), condition);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("action")), action);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("severity")), severity);
        alertRulesModel->setData(alertRulesModel->index(row, alertRulesModel->fieldIndex("enabled")), 1);

        settings.endGroup();
        importedCount++;
    }

    if (!alertRulesModel->submitAll()) {
        QMessageBox::critical(this, "错误", "规则导入失败：" + alertRulesModel->lastError().text());
        LogManager::logError("规则导入失败：" + alertRulesModel->lastError().text());
        return false;
    }

    QMessageBox::information(this, "导入完成",
        QString("成功导入 %1 条规则，跳过 %2 条重复或无效规则").arg(importedCount).arg(skippedCount));

    LogManager::logOperation(-1, "导入规则",
                             QString("从 %1 导入 %2 条规则，跳过 %3 条").arg(filename).arg(importedCount).arg(skippedCount));

    // 刷新规则模型
    alertRulesModel->select();

    return true;
}

bool AlertManager::isRuleExists(const QString& deviceId, const QString& description,
                               const QString& condition, const QString& action, const QString& severity)
{
    QSqlQuery query;
    query.prepare("SELECT COUNT(*) FROM alarm_rules WHERE device_id = ? AND description = ? "
                  "AND condition = ? AND action = ? AND severity = ?");
    query.addBindValue(deviceId);
    query.addBindValue(description);
    query.addBindValue(condition);
    query.addBindValue(action);
    query.addBindValue(severity);

    if (query.exec() && query.next()) {
        return query.value(0).toInt() > 0;
    }
    return false;
}

bool AlertManager::exportRulesToIni(const QString& filePath)
{
    QSettings settings(filePath, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");

    // 清空现有配置
    settings.clear();

    QSqlQuery query;
    query.prepare("SELECT rule_id, device_id, description, condition, action, severity, is_enabled FROM alarm_rules");

    if (!query.exec()) {
        qDebug() << "查询规则失败:" << query.lastError().text();
        return false;
    }

    int exportCount = 0;
    while (query.next()) {
        int ruleId = query.value(0).toInt();
        int deviceId = query.value(1).toInt();
        QString description = query.value(2).toString();
        QString condition = query.value(3).toString();
        QString action = query.value(4).toString();
        QString severity = query.value(5).toString();
        bool isEnabled = query.value(6).toBool();

        QString groupName = QString("Rule_%1").arg(ruleId);
        settings.beginGroup(groupName);
        settings.setValue("device_id", deviceId);
        settings.setValue("description", description);
        settings.setValue("condition", condition);
        settings.setValue("action", action);
        settings.setValue("severity", severity);
        settings.setValue("is_enabled", isEnabled);
        settings.endGroup();

        exportCount++;
    }

    settings.sync();

    if (exportCount > 0) {
        LogManager::logOperation(-1, "导出告警规则", QString("成功导出%1条规则").arg(exportCount));
        return true;
    }

    return false;
}

void AlertManager::syncRuleToIni(int ruleId)
{
    QString iniPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/alarm_rules.ini";
    QSettings settings(iniPath, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");

    QSqlQuery query;
    query.prepare("SELECT device_id, description, condition, action, severity, is_enabled FROM alarm_rules WHERE rule_id = ?");
    query.addBindValue(ruleId);

    if (query.exec() && query.next()) {
        int deviceId = query.value(0).toInt();
        QString description = query.value(1).toString();
        QString condition = query.value(2).toString();
        QString action = query.value(3).toString();
        QString severity = query.value(4).toString();
        bool isEnabled = query.value(5).toBool();

        QString groupName = QString("Rule_%1").arg(ruleId);
        settings.beginGroup(groupName);
        settings.setValue("device_id", deviceId);
        settings.setValue("description", description);
        settings.setValue("condition", condition);
        settings.setValue("action", action);
        settings.setValue("severity", severity);
        settings.setValue("is_enabled", isEnabled);
        settings.endGroup();

        settings.sync();
    }
}

void AlertManager::deleteRuleFromIni(int ruleId)
{
    QString iniPath = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation) + "/alarm_rules.ini";
    QSettings settings(iniPath, QSettings::IniFormat);
    settings.setIniCodec("UTF-8");

    QString groupName = QString("Rule_%1").arg(ruleId);
    settings.remove(groupName);
    settings.sync();
}

void AlertManager::onImportRules()
{
    QString filePath = QFileDialog::getOpenFileName(this, "选择规则配置文件", "", "INI Files (*.ini)");

    if (filePath.isEmpty()) {
        return;
    }

    if (importRulesFromIni(filePath)) {
        QMessageBox::information(this, "成功", "规则导入成功!");
        ui->statusbar->showMessage("规则导入完成");
    } else {
        QMessageBox::warning(this, "失败", "规则导入失败,请检查文件格式。");
        LogManager::logError("导入告警规则失败: 文件格式错误或无有效规则");
    }
}

void AlertManager::onExportRules()
{
    QString defaultPath = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/alarm_rules.ini";
    QString filePath = QFileDialog::getSaveFileName(this, "导出规则配置文件", defaultPath, "INI Files (*.ini)");

    if (filePath.isEmpty()) {
        return;
    }

    if (exportRulesToIni(filePath)) {
        QMessageBox::information(this, "成功", "规则导出成功!");
        ui->statusbar->showMessage("规则导出完成: " + filePath);
    } else {
        QMessageBox::warning(this, "失败", "规则导出失败。");
        LogManager::logError("导出告警规则失败");
    }
}

void AlertManager::onAcknowledgeAlert()
{
    QModelIndex index = ui->tableViewCurrentAlerts->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请选择要确认的告警");
        LogManager::logError("确认告警失败: 未选择告警");
        return;
    }

    int row = index.row();
    int recordId = currentAlertsModel->data(currentAlertsModel->index(row, currentAlertsModel->fieldIndex("record_id"))).toInt();

    currentAlertsModel->setData(currentAlertsModel->index(row, currentAlertsModel->fieldIndex("status")), "acknowledged");

    if (currentAlertsModel->submitAll()) {
        ui->statusbar->showMessage("告警已确认");
        LogManager::logOperation(-1, "确认告警", QString("告警已确认,记录ID: %1").arg(recordId));
    } else {
        QMessageBox::critical(this, "错误", "确认告警失败: " + currentAlertsModel->lastError().text());
        LogManager::logError("确认告警失败: " + currentAlertsModel->lastError().text());
    }
}

void AlertManager::onResolveAlert()
{
    QModelIndex index = ui->tableViewCurrentAlerts->currentIndex();
    if (!index.isValid()) {
        QMessageBox::warning(this, "警告", "请选择要解决的告警");
        LogManager::logError("解决告警失败: 未选择告警");
        return;
    }

    int row = index.row();
    int recordId = currentAlertsModel->data(currentAlertsModel->index(row,
                   currentAlertsModel->fieldIndex("record_id"))).toInt();
    int ruleId = currentAlertsModel->data(currentAlertsModel->index(row,
                 currentAlertsModel->fieldIndex("rule_id"))).toInt();

    currentAlertsModel->setData(currentAlertsModel->index(row,
                                currentAlertsModel->fieldIndex("status")), "resolved");
    currentAlertsModel->setData(currentAlertsModel->index(row,
                                currentAlertsModel->fieldIndex("resolved_time")),
                                QDateTime::currentDateTime());

    if (currentAlertsModel->submitAll()) {
        // ✅ 从活跃告警列表中移除
        m_activeAlertsByRule.remove(ruleId);

        // ✅ 检查是否还有其他活跃告警
        if (m_activeAlertsByRule.isEmpty()) {
            deactivateBuzzer();
        }

        ui->statusbar->showMessage("告警已解决");
        LogManager::logOperation(-1, "解决告警",
                               QString("告警已解决,记录ID: %1").arg(recordId));

        // 刷新当前告警和历史列表
        currentAlertsModel->setFilter("status IN ('active', 'acknowledged')");
        currentAlertsModel->select();

        QDateTime oneWeekAgo = QDateTime::currentDateTime().addDays(-7);
        alertHistoryModel->setFilter(QString("trigger_time >= '%1'")
                                    .arg(oneWeekAgo.toString("yyyy-MM-dd HH:mm:ss")));
        alertHistoryModel->select();

        QMessageBox::information(this, "提示", "告警已成功解决并归档到历史记录。");
    } else {
        QMessageBox::critical(this, "错误", "解决告警失败: " +
                            currentAlertsModel->lastError().text());
        LogManager::logError("解决告警失败: " + currentAlertsModel->lastError().text());
    }
}

void AlertManager::onQueryHistory()
{
    QDateTime startTime = ui->dateTimeEditHistoryStart->dateTime();
    QDateTime endTime = ui->dateTimeEditHistoryEnd->dateTime();

    if (startTime > endTime) {
        QMessageBox::warning(this, "警告", "开始时间不能晚于结束时间");
        LogManager::logError("查询告警历史失败: 时间范围错误");
        return;
    }

    QString filter = QString("trigger_time >= '%1' AND trigger_time <= '%2'")
                    .arg(startTime.toString("yyyy-MM-dd HH:mm:ss"))
                    .arg(endTime.toString("yyyy-MM-dd HH:mm:ss"));

    alertHistoryModel->setFilter(filter);

    if (alertHistoryModel->select()) {
        ui->tableViewAlertHistory->resizeColumnsToContents();
        ui->statusbar->showMessage(QString("查询到 %1 条告警记录").arg(alertHistoryModel->rowCount()));
        LogManager::logOperation(-1, "查询告警历史",
                               QString("找到%1条记录").arg(alertHistoryModel->rowCount()));
    } else {
        QMessageBox::critical(this, "错误", "查询告警历史失败: " + alertHistoryModel->lastError().text());
        LogManager::logError("查询告警历史失败: " + alertHistoryModel->lastError().text());
    }
}

void AlertManager::onAlertStatusChanged(int index)
{
    QString statusFilter;
    switch (index) {
    case 0: statusFilter = ""; break;
    case 1: statusFilter = "status = 'active'"; break;
    case 2: statusFilter = "status = 'acknowledged'"; break;
    case 3: statusFilter = "status = 'resolved'"; break;
    }

    currentAlertsModel->setFilter(statusFilter);
    currentAlertsModel->select();

    QString statusText;
    switch (index) {
    case 0: statusText = "所有状态"; break;
    case 1: statusText = "活跃状态"; break;
    case 2: statusText = "已确认状态"; break;
    case 3: statusText = "已解决状态"; break;
    }

    LogManager::logOperation(-1, "告警状态筛选", QString("筛选状态: %1").arg(statusText));
}

void AlertManager::onRuleFilterChanged()
{
    if (ui->checkBoxEnabled->isChecked()) {
        alertRulesModel->setFilter("is_enabled = 1");
        LogManager::logOperation(-1, "告警规则筛选", "只显示启用规则");
    } else {
        alertRulesModel->setFilter("");
        LogManager::logOperation(-1, "告警规则筛选", "显示所有规则");
    }
    alertRulesModel->select();
}

void AlertManager::refreshAlerts()
{
    currentAlertsModel->select();
    static int refreshCount = 0;
    refreshCount++;
    if (refreshCount % 12 == 0) {
        LogManager::logSystem("告警管理模块", "告警列表定时刷新");
    }
}

void AlertManager::autoResolveAlert(int ruleId, const QVariantMap& sensorData)
{
    if (!m_activeAlertsByRule.contains(ruleId)) {
        return;
    }

    int recordId = m_activeAlertsByRule[ruleId];

    // 更新告警记录状态为已解决
    QSqlQuery updateQuery;
    updateQuery.prepare("UPDATE alarm_records SET status = 'resolved', "
                       "resolved_time = ? WHERE record_id = ?");
    updateQuery.addBindValue(QDateTime::currentDateTime());
    updateQuery.addBindValue(recordId);

    if (updateQuery.exec()) {
        // 从活跃告警列表中移除
        m_activeAlertsByRule.remove(ruleId);

        // ✅ 检查是否还有其他活跃告警
        if (m_activeAlertsByRule.isEmpty()) {
            // 没有活跃告警了，关闭蜂鸣器
            deactivateBuzzer();
        }

        LogManager::logSystem("告警管理模块",
                            QString("自动解决告警 | 规则ID:%1 | 记录ID:%2 | 设备ID:%3")
                            .arg(ruleId)
                            .arg(recordId)
                            .arg(sensorData["device_id"].toInt()));

        // 刷新当前告警和历史列表
        currentAlertsModel->select();
        alertHistoryModel->select();
    } else {
        LogManager::logError(QString("自动解决告警失败: %1").arg(updateQuery.lastError().text()));
    }
}

// ✅ 新增：激活蜂鸣器
void AlertManager::activateBuzzer()
{
    if (!m_pageControl) {
        qDebug() << "无法激活蜂鸣器: PageControl未连接";
        return;
    }

    // ⚠️ 只更新UI状态，不直接发送串口指令
    // UI状态改变会触发 onQuickBuzzerToggle() 自动发送指令
    m_pageControl->updateBuzzerStatusFromAlert(true);

    LogManager::logSystem("告警管理模块", "蜂鸣器已自动开启");
}

// ✅ 新增：关闭蜂鸣器
void AlertManager::deactivateBuzzer()
{
    if (!m_pageControl) {
        qDebug() << "无法关闭蜂鸣器: PageControl未连接";
        return;
    }

    // ⚠️ 只更新UI状态，不直接发送串口指令
    // UI状态改变会触发 onQuickBuzzerToggle() 自动发送指令
    m_pageControl->updateBuzzerStatusFromAlert(false);

    LogManager::logSystem("告警管理模块", "蜂鸣器已自动关闭");
}
